package com.llkj.contractmanagement.http;

import android.content.Context;
import android.util.Log;

import com.llkj.contractmanagement.model.BaseBean;
import com.llkj.contractmanagement.utils.GsonUtil;
import com.llkj.contractmanagement.utils.LogUtil;
import com.llkj.contractmanagement.utils.ToastUtil;
import com.llkj.contractmanagement.utils.Utils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.HashMap;
import java.util.Set;

import okhttp3.Call;
import okhttp3.Request;

/**
 * 异步数据请求
 */
public class AnsynHttpRequest {
    public static final int POST = 1; // post 提交
    public static final int GET = 2; // get 提交

    /**
     * @param sendType 请求类型
     * @param url      请求地址
     * @param map      参数
     * @param callBack 异步回调
     * @param i        请求的方法对应的int值（整个项目中唯一不重复的）
     */
    public static void requestGetOrPost(int sendType, Context context, String url,
                                        HashMap<String, String> map, final ObserverCallBack callBack, final int i) {
        //判断网络
        if (!Utils.isNetworkConnected(context)) {
            ToastUtil.makeShortText(context, "请检查网络!");
            return;
        }
        url = Utf8URLencode(url);
        switch (sendType) {
            case POST:
                Log.e("Log", "request::" + url);
                if (map != null) {
                    Set<String> keySet = map.keySet();
                    for (String key : keySet) {
                        String value = map.get(key);
                        if (value == null) {
                            continue;
                        }
                        value = value.replace(" ", "");
                        Log.e("Log", "params::" + key + " => " + value);
                    }
                }
                OkHttpUtils
                        .post().url(url).params(map).tag(context).build().connTimeOut(15000)
                        .execute(new StringCallback() {

                            @Override
                            public void onBefore(Request request) {
                                callBack.onBefore(i);
                            }

                            @Override
                            public void onError(Call call, Exception e) {
                                callBack.onError(e);
                            }

                            @Override
                            public void onResponse(String response) {
                                Log.e("Log", "POST:" + response);
                                BaseBean db = GsonUtil.GsonToBean(response, BaseBean.class);
                                if (db.getState() == 1) {
                                    //成功接口
                                    callBack.onSuccessHttp(response, i);
                                } else {
                                    if (db.getState() == -2) {
                                        callBack.onConflict(db.getMessage());
                                    } else {
                                        callBack.onFailureHttp(db.getMessage());
                                    }
                                }
                            }
                        });
                break;
            case GET:
                StringBuffer sb = new StringBuffer();
                sb.append(url);
                if (map != null) {
                    if (!url.endsWith("?")) {
                        sb.append("&");
                    }
                    Set<String> keySet = map.keySet();
                    for (String key : keySet) {
                        String value = map.get(key);
                        if (value == null) {
                            continue;
                        }
                        value = value.replace(" ", "");
                        sb.append(key).append("=").append(value).append("&");
                    }
                    if (sb.toString().endsWith("&")) {
                        sb.deleteCharAt(sb.toString().length() - 1);
                    }
                }
                Log.e("Log", "request::" + sb.toString());
                OkHttpUtils
                        .get().url(sb.toString()).tag(context).build().connTimeOut(15000)
                        .execute(new StringCallback() {
                            @Override
                            public void onBefore(Request request) {
                                callBack.onBefore(i);
                            }

                            @Override
                            public void onError(Call call, Exception e) {
                                callBack.onError(e);
                            }

                            @Override
                            public void onResponse(String response) {
                                Log.e("Log", "GET:" + response);
                                BaseBean db = GsonUtil.GsonToBean(response, BaseBean.class);
                                if (db.getState() == 1) {
                                    //成功接口
                                    callBack.onSuccessHttp(response, i);
                                } else {
                                    if (db.getState() == -2) {
                                        callBack.onConflict(db.getMessage());
                                    } else {
                                        callBack.onFailureHttp(db.getMessage());
                                    }
                                }
                            }
                        });
                break;
            default:
                break;
        }

    }

    /**
     * Utf8URL编码
     *
     * @return
     */
    static String Utf8URLencode(String text) {
        StringBuffer result = new StringBuffer();
        for (int i = 0; i < text.length(); i++) {
            char c = text.charAt(i);
            if (c >= 0 && c <= 255) {
                result.append(c);
            } else {
                byte[] b = new byte[0];
                try {
                    b = Character.toString(c).getBytes("UTF-8");
                } catch (Exception ex) {
                }
                for (int j = 0; j < b.length; j++) {
                    int k = b[j];
                    if (k < 0)
                        k += 256;
                    result.append("%" + Integer.toHexString(k).toUpperCase());
                }
            }
        }
        return result.toString();
    }

    private static void getUrlLog(String url, HashMap<String, String> map) {
        StringBuffer sb = new StringBuffer();
        sb.append(url);
        if (map != null) {
            if (!url.endsWith("?")) {
                sb.append("&");
            }
            Set<String> keySet = map.keySet();
            for (String key : keySet) {
                String value = map.get(key);
                if (value == null) {
                    continue;
                }
                value = value.replace(" ", "");
                sb.append(key).append("=").append(value).append("&");
            }
            if (sb.toString().endsWith("&")) {
                sb.deleteCharAt(sb.toString().length() - 1);
            }
        }
        Log.e("Log", "request::" + sb.toString());
    }

}
